package com.wstuo.common.tools.dao;

import com.wstuo.common.tools.dto.EmailMessageQueryDTO;
import com.wstuo.common.tools.entity.EmailMessage;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.util.StringUtils;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 邮箱信息DAO接口
 * @author Mars
 *
 */
public class EmailDAO
    extends BaseDAOImplHibernate<EmailMessage>
    implements IEmailDAO
{
    /**
     * 获取数据库接收邮件的最后时间
     * @param receiveMail
     * @return EmailMessage
     */
    public EmailMessage findLastestReceiveDate(String receiveMail)
    {
    	EmailMessage message = null;
        String hql = "From EmailMessage where folderName='INBOX' and toUser like '%"+receiveMail+"%' and dataFlag=0 order by receiveDate desc";
        List<EmailMessage> list = getHibernateTemplate(  ).find( hql );
        if ( list.size(  ) > 0 )
        {
        	message = list.get( 0 );
        }
        return message;
    }

   
    /**
     * 邮件信息分页查询
     * @param dto 查询条件DTO
     * @param start 查询第几页
     * @param limit 每页行数
     * @param sidx
     * @param sord
     * @return PageDTO
     */
    public PageDTO findPager( EmailMessageQueryDTO dto, int start, int limit, String sidx, String sord  )
    {
        final DetachedCriteria dc = DetachedCriteria.forClass( EmailMessage.class );

        if ( dto != null )
        {
        	//基础属性
            searchBaseAttribute(dto, dc);
            //根据时间搜索
            searchByTime(dto, dc);
        }

      //排序
        if(StringUtils.hasText(sord)&&StringUtils.hasText(sidx)){
        	//add mars 
        	if(sidx.equals("toRequest")){
        		sidx="isToRequest";
        	}
            if(sord.equals("desc"))
            	dc.addOrder(Order.desc(sidx));
            else
            	dc.addOrder(Order.asc(sidx));
        }
        return super.findPageByCriteria( dc, start, limit );
    }

    /**
     * 基础属性 
     * @param dto
     * @param dc
     */
	private void searchBaseAttribute(EmailMessageQueryDTO dto,
			final DetachedCriteria dc) {
		if ( StringUtils.hasText( dto.getSubject() ) )
		{
		    dc.add( Restrictions.or( Restrictions.like("subject",dto.getSubject(),MatchMode.ANYWHERE ),
		                             Restrictions.like("keyword",dto.getSubject(),MatchMode.ANYWHERE ) ));
		}
		if(StringUtils.hasText(dto.getContent())){
			dc.add(Restrictions.like("content", dto.getContent(), MatchMode.ANYWHERE));
		}
		if(StringUtils.hasText( dto.getFolderName() )){
			dc.add(Restrictions.eq("folderName",dto.getFolderName()));
		}
		if(StringUtils.hasText(dto.getModuleCode()) || StringUtils.hasText(dto.getModuleEno())){
			dc.add(Restrictions.or(
					Restrictions.eq("moduleCode",dto.getModuleCode()), 
					Restrictions.eq("moduleCode",dto.getModuleEno())
				));
		}
		if(dto.getKeyword()!=null){
			dc.add(Restrictions.like("keyword", dto.getKeyword(),MatchMode.ANYWHERE));
		}
		if(dto.getToUser()!=null){
			dc.add(Restrictions.like("toUser", dto.getToUser(),MatchMode.ANYWHERE));
		}
		if(dto.getFromUser()!=null){
			dc.add(Restrictions.like("fromUser", dto.getFromUser(),MatchMode.ANYWHERE));
		}
	}

    /**
     * 根据时间搜索
     * @param dto
     * @param dc
     */
	private void searchByTime(EmailMessageQueryDTO dto,
			final DetachedCriteria dc) {
		
		  if (dto.getReceiveStartDate() == null && dto.getReceiveEndDate()!=null) {
	
	      	Calendar endTimeCl=new GregorianCalendar();
	      	endTimeCl.setTime(dto.getReceiveEndDate());
	      	endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE)+1);
	
	          dc.add(Restrictions.le("receiveDate",endTimeCl.getTime()));
	      }
	      
	      if (dto.getReceiveStartDate() != null && dto.getReceiveEndDate()!=null) {
	
	      	
	      	Calendar endTimeCl=new GregorianCalendar();
	      	endTimeCl.setTime(dto.getReceiveEndDate());
	      	endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE)+1);
	
	          dc.add(Restrictions.and(Restrictions.le("receiveDate",endTimeCl.getTime()),Restrictions.ge("receiveDate", dto.getReceiveStartDate())));
	      }
		//接收时间搜索
		if (dto.getReceiveStartDate() != null && dto.getReceiveEndDate()==null) {
		    dc.add(Restrictions.ge("receiveDate", dto.getReceiveStartDate()));
		}
		//发送时间搜索
		if (dto.getSendStartDate() != null && dto.getSendEndDate()==null) {
		    dc.add(Restrictions.ge("sendDate", dto.getSendStartDate()));
		}
		if (dto.getSendStartDate() == null && dto.getSendEndDate()!=null) {

			Calendar endTimeCl=new GregorianCalendar();
			endTimeCl.setTime(dto.getSendEndDate());
			endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE)+1);
  
		    dc.add(Restrictions.le("sendDate",endTimeCl.getTime()));
		}
		
		if (dto.getSendStartDate() != null && dto.getSendEndDate()!=null) {

			
			Calendar endTimeCl=new GregorianCalendar();
			endTimeCl.setTime(dto.getSendEndDate());
			endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE)+1);
  
		    dc.add(Restrictions.and(Restrictions.le("sendDate",endTimeCl.getTime()),Restrictions.ge("sendDate", dto.getSendStartDate())));
		}
	}
}
